"""
Elasticsearch同步管理器
提供文章与ES之间的同步功能
"""
from elasticsearch import Elasticsearch
from django.conf import settings
import logging

# 配置日志
logger = logging.getLogger('elasticsearch')


class ElasticsearchSyncManager:
    """Elasticsearch同步管理类"""

    ES_HOST = 'http://localhost:9200'
    INDEX_NAME = 'medical_articles'

    @classmethod
    def get_es_client(cls):
        """获取ES客户端连接"""
        return Elasticsearch(cls.ES_HOST)

    @classmethod
    def ensure_index_exists(cls):
        """确保索引存在，如不存在则创建"""
        es = cls.get_es_client()

        if not es.indices.exists(index=cls.INDEX_NAME):
            # 创建索引配置
            index_settings = {
                "settings": {"number_of_shards": 1, "number_of_replicas": 0},
                "mappings": {
                    "properties": {
                        "id": {"type": "keyword"},
                        "title": {"type": "text", "analyzer": "standard"},
                        "content": {"type": "text", "analyzer": "standard"},
                        "author": {"type": "text"},
                        "department_name": {"type": "keyword"},
                        "tags": {"type": "text", "analyzer": "standard"},
                        "status": {"type": "keyword"},
                        "view_count": {"type": "integer"},
                        "like_count": {"type": "integer"},
                        "created_at": {"type": "date"},
                        "updated_at": {"type": "date"}
                    }
                }
            }

            # 创建索引
            es.indices.create(index=cls.INDEX_NAME, body=index_settings)
            logger.info(f"创建ES索引: {cls.INDEX_NAME}")

        return True

    @classmethod
    def sync_article_to_es(cls, article, delete=False):
        """
        同步单篇文章到ES
        :param article: MedicalArticle实例
        :param delete: 如果为True则删除文档，否则创建或更新
        """
        if not article or not getattr(article, 'id', None):
            logger.error("无法同步文章到ES: 文章对象为空或没有ID")
            return False

        doc_id = str(article.id)
        es = cls.get_es_client()

        try:
            # 确保索引存在
            cls.ensure_index_exists()

            if delete:
                # 从ES中删除文档
                if es.exists(index=cls.INDEX_NAME, id=doc_id):
                    es.delete(index=cls.INDEX_NAME, id=doc_id)
                    logger.info(f"从ES中删除文章: id={doc_id}")
                return True

            # 构建文档数据
            doc = {
                "id": article.id,
                "title": article.title,
                "content": article.content,
                "author": article.author,
                "department_name": article.department.name if article.department else "",
                "tags": article.tags,
                "status": article.status,
                "view_count": article.view_count,
                "like_count": article.like_count,
                "created_at": article.created_at.isoformat() if article.created_at else None,
                "updated_at": article.updated_at.isoformat() if article.updated_at else None
            }

            # 创建或更新文档
            es.index(index=cls.INDEX_NAME, id=doc_id, body=doc, refresh=True)
            logger.info(f"同步文章到ES: id={doc_id}, title={article.title}")
            return True

        except Exception as e:
            logger.error(f"同步文章到ES失败: id={doc_id}, error={str(e)}")
            # 在开发环境打印错误
            if settings.DEBUG:
                import traceback
                logger.error(traceback.format_exc())
            return False